using Microsoft.AspNetCore.Mvc;
using RobotInspection.Interfaces;
using System;
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;
using _RobotInspection.Attributes;
using _RobotInspection.Models;

namespace RobotInspection.Controllers
{
    /// <summary>
    /// 点检记录自动生成控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class InspectionRecordGeneratorController : ControllerBase
    {
        private readonly IInspectionRecordGeneratorService _generatorService;

        public InspectionRecordGeneratorController(IInspectionRecordGeneratorService generatorService)
        {
            _generatorService = generatorService;
        }

        /// <summary>
        /// 自动生成当天的点检记录
        /// </summary>
        /// <returns>生成结果</returns>
        [HttpPost("generate-today")]
        [ApiStatus(ApiStatusEnum.Developing)]
        public async Task<ActionResult<ApiResponse<object>>> GenerateToday()
        {
            return await _generatorService.GenerateInspectionRecords();
        }

        /// <summary>
        /// 为指定日期生成点检记录
        /// </summary>
        /// <param name="targetDate">目标日期 (格式: yyyy-MM-dd)</param>
        /// <returns>生成结果</returns>
        [HttpPost("generate-by-date")]
        [ApiStatus(ApiStatusEnum.Developing)]
        public async Task<ActionResult<ApiResponse<object>>> GenerateByDate([Required] DateTime targetDate)
        {
            if (targetDate == default)
            {
                return BadRequest(ApiResponse<object>.Error("请提供有效的目标日期", 400));
            }

            return await _generatorService.GenerateInspectionRecords(targetDate);
        }

        /// <summary>
        /// 为指定计划和日期生成点检记录
        /// </summary>
        /// <param name="planId">计划ID</param>
        /// <param name="targetDate">目标日期 (格式: yyyy-MM-dd)</param>
        /// <returns>生成结果</returns>
        [HttpPost("generate-for-plan")]
        [ApiStatus(ApiStatusEnum.Developing)]
        public async Task<ActionResult<ApiResponse<object>>> GenerateForPlan([Required] long planId, [Required] DateTime targetDate)
        {
            if (planId <= 0)
            {
                return BadRequest(ApiResponse<object>.Error("请提供有效的计划ID", 400));
            }

            if (targetDate == default)
            {
                return BadRequest(ApiResponse<object>.Error("请提供有效的目标日期", 400));
            }

            return await _generatorService.GenerateInspectionRecordsForPlan(planId, targetDate);
        }

        /// <summary>
        /// 批量生成指定日期范围内的点检记录
        /// </summary>
        /// <param name="startDate">开始日期 (格式: yyyy-MM-dd)</param>
        /// <param name="endDate">结束日期 (格式: yyyy-MM-dd)</param>
        /// <returns>生成结果</returns>
        [HttpPost("generate-batch")]
        [ApiStatus(ApiStatusEnum.Developing)]
        public async Task<ActionResult<ApiResponse<object>>> GenerateBatch(
            [Required] DateTime startDate,
            [Required] DateTime endDate)
        {
            if (startDate == default || endDate == default)
            {
                return BadRequest(ApiResponse<object>.Error("请提供有效的开始和结束日期", 400));
            }

            if (startDate > endDate)
            {
                return BadRequest(ApiResponse<object>.Error("开始日期不能大于结束日期", 400));
            }

            var totalDays = (endDate - startDate).Days + 1;
            if (totalDays > 31)
            {
                return BadRequest(ApiResponse<object>.Error("批量生成的日期范围不能超过31天", 400));
            }

            var results = new List<object>();
            var successCount = 0;
            var failCount = 0;

            for (var date = startDate; date <= endDate; date = date.AddDays(1))
            {
                try
                {
                    var result = await _generatorService.GenerateInspectionRecords(date);
                    if (result.Value?.Code == 200)
                    {
                        successCount++;
                        results.Add(new { Date = date.ToString("yyyy-MM-dd"), Status = "成功", Message = result.Value.Message });
                    }
                    else
                    {
                        failCount++;
                        results.Add(new { Date = date.ToString("yyyy-MM-dd"), Status = "失败", Message = result.Value?.Message ?? "未知错误" });
                    }
                }
                catch (Exception ex)
                {
                    failCount++;
                    results.Add(new { Date = date.ToString("yyyy-MM-dd"), Status = "异常", Message = ex.Message });
                }
            }

            return Ok(ApiResponse<object>.Success(new
            {
                TotalDays = totalDays,
                SuccessCount = successCount,
                FailCount = failCount,
                Details = results
            }, $"批量生成完成，成功: {successCount} 天，失败: {failCount} 天"));
        }
    }
}